package com.lakeworks.web.controller.core;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lakeworks.common.annotation.Anonymous;
import com.lakeworks.common.constant.HttpStatus;
import com.lakeworks.common.core.controller.BaseController;
import com.lakeworks.common.core.domain.AjaxResult;
import com.lakeworks.common.domain.channel.ExpressVo;
import com.lakeworks.common.domain.channel.ProductStatus;
import com.lakeworks.common.domain.channel.ShipmentImport;
import com.lakeworks.common.domain.channel.ShipmentStatus;
import com.lakeworks.common.enums.ExpressStatus;
import com.lakeworks.common.enums.OprProductType;
import com.lakeworks.common.enums.ShipMentType;
import com.lakeworks.common.utils.BarcodeGenerator;
import com.lakeworks.common.utils.StringUtils;
import com.lakeworks.common.utils.http.HttpUtils;
import com.lakeworks.domain.OprPickup;
import com.lakeworks.domain.OprProduct;
import com.lakeworks.domain.OprShipment;
import com.lakeworks.domain.SysProduct;
import com.lakeworks.domain.vo.ClothInfo;
import com.lakeworks.mapper.OprPickupMapper;
import com.lakeworks.mapper.OprProductMapper;
import com.lakeworks.mapper.OprShipmentMapper;
import com.lakeworks.mapper.TktTicketMapper;
import com.lakeworks.service.*;
import com.lakeworks.service.api.DetectMethodAnnotation;
import com.lakeworks.service.api.MerchantAsync;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.alibaba.fastjson.JSON.parseObject;
import static org.springframework.http.ResponseEntity.status;

@RestController
@RequestMapping("/")
@Validated
public class AnonymityController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ITktTicketService tktTicketService;

    @Autowired
    private DetectMethodAnnotation detectMethodAnnotation;

    @Autowired
    private IThirdChannelService thirdChannelService;

    @Autowired
    private MerchantAsync merchantAsync;

    @Autowired
    private TktTicketMapper tktTicketMapper;

    @Autowired
    private OprProductMapper oprProductMapper;

    @Autowired
    private OprPickupMapper oprPickupMapper;

    @Autowired
    private BarcodeGenerator barcodeGenerator;

    @Autowired
    private IOprProductService oprProductService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ITktNodeService tktNodeService;

    @Autowired
    private OprShipmentMapper oprShipmentMapper;

    @Autowired
    private ISysChannelService sysChannelService;

    @Autowired
    private IOprIndexService oprIndexService;

    @Anonymous
    @GetMapping("noop")
    public ResponseEntity testLink(){
        return status(HttpStatus.SUCCESS).build();
    }

    @Anonymous
    @PostMapping("hold/order")
    public AjaxResult holdingOrder(String orderNo, boolean code){
        return AjaxResult.success(oprProductService.holdingOrder(orderNo,code));
    }

    @Anonymous
    @GetMapping("test")
    public AjaxResult testMethod(){
//        List<String> statuses = new ArrayList<>();
//        statuses.add("5");
//        statuses.add("7");
//        statuses.add("10");
//        PageInfo<ClothInfo> oprProducts = oprProductService.getOprProducts(ClothInfo.builder().statuses(statuses).build());
//        System.out.println(oprProducts.getList());

//        System.out.println(oprIndexService.getVerifyCount(1));
        //System.out.println(oprIndexService.getProductCount("TOWASH", null));
//        System.out.println(oprIndexService.getshipmentCount("PENDING", 24));
//        System.out.println(oprIndexService.getNotReceivedCount(1,24));
//        System.out.println(oprIndexService.getCustomerTimeoutCount(1,24));
//        System.out.println(oprIndexService.getProductionTimeoutCount(1,24));
//        System.out.println(oprIndexService.getTendency());
//        Enumeration<String> headerNames = request.getHeaderNames();
//        // 打印请求头信息
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            String headerValue = request.getHeader(headerName);
//            logger.info("test header--"+ headerName + ": " +headerValue);
//        }
//        String shipmentNo = "DO424494988110";
//        ShipmentImport anImport = new ShipmentImport();
//        List<String> barcodeList = new ArrayList<>();
//        barcodeList.add("1200100009562");
//        anImport.setBarcodeList(barcodeList);
//        anImport.setRecycle(true);
//        anImport.setComment("waterfall");
//        thirdChannelService.syncShipment(shipmentNo,anImport);

//        String prefix = "";
//        List<SysProduct> sysProducts = new ArrayList<>();
//        String result = sysChannelService.getPrefixAndProducts("https://huangguoshu.dajingxiapp.cn", "lMzo1oI6ab4J", "XyOHXfUU35AUxyK3ndFNSK7I8vtP1pYF");
//        //System.out.println(result);
//        if(StringUtils.isNotBlank(result)){
//            JSONObject jsonObject = parseObject(result);
//            prefix = jsonObject.getString("prefix");
//            JSONArray jsonArray = jsonObject.getJSONArray("productList");
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObj = jsonArray.getJSONObject(i);
//                SysProduct build = SysProduct.builder()
//                        .channelId(1l)
//                        .code(jsonObj.getString("code"))
//                        .name(jsonObj.getString("name"))
//                        .category(jsonObj.getString("category"))
//                        .picture(jsonObj.getString("picture"))
//                        .build();
//                System.out.println(build.toString());
//            }
//
//        }
//        System.out.println(prefix);



//        JSONObject jsonObject = parseObject(result);
//        brand = parseObject(jsonObject.getString("merchant")).getString("name");
//        userPhone = jsonObject.getString("phone");
//        userName = jsonObject.getString("name");
//        userComment = jsonObject.getString("comment");
        //HttpUtils.sendGetRequest("lMzo1oI6ab4J","XyOHXfUU35AUxyK3ndFNSK7I8vtP1pYF","http://192.168.8.130:8080/waterfall_sso_war_exploded/feishu/apps");
        //applicationContext.publishEvent(new DistributionEvent(this,"testqqqqq"));
//        Boolean leave = merchantAsync.isLeave("R022344716276084", 1l);
//        System.out.println(leave);
        //thirdChannelService.expressStatus(ExpressVo.builder().expressNo("SF123124").status(ExpressStatus.PICKED.name()).build());
        return AjaxResult.success();
    }

    @Anonymous
    @PostMapping("ticket/close")
    public AjaxResult closeTicket(Long id){
        return tktTicketService.closeTicket(id);
    }



    @Anonymous
    @PostMapping("product/state")
    public AjaxResult productState(@RequestBody List<String> barcodes){
        System.out.println(barcodes);
        AtomicInteger i = new AtomicInteger();
        StringBuilder builder = new StringBuilder();
        if(!CollectionUtils.isEmpty(barcodes)){
             barcodes.forEach(b->{
                 OprProduct product = oprProductMapper.queryByBarcode(b);
                 OprPickup oprPickup = oprPickupMapper.selectOprPickupById(product.getPickupId());
                 if(oprPickup != null){
                     String result = merchantAsync.backProductState(ProductStatus.builder()
                             .pickupNo(oprPickup.getChPickupNo())
                             .barcode(b)
                             .status(OprProductType.PLACED.name())
                             .state(0)
                             .noWash(false)
                             .build(), oprPickup.getChannelId());
                     builder.append("barcode::").append(b).append("result::").append(result).append("count").append(i.getAndIncrement());
                 }
             });
         }
        return success(builder.toString());
    }





   /* @Anonymous
    @PostMapping("out/factory")
    public AjaxResult outFactory(@RequestBody List<String> expressNos){
        System.out.println(expressNos);
        if(!CollectionUtils.isEmpty(expressNos)){
            expressNos.forEach(e->{
                AjaxResult result = oprProductService.outFactory(e, true);
                System.out.println(result.get("msg"));
            });
        }
        return success();
    }


    @Anonymous
    @PostMapping("out/shipment")
    public AjaxResult outshipment(@RequestBody List<String> expressNos){
        System.out.println(expressNos);
        if(!CollectionUtils.isEmpty(expressNos)){
            expressNos.forEach(e->{
                OprShipment shipment = oprShipmentMapper.queryByExpressNo(e);
                List<OprProduct> products = oprProductMapper.queryByShipmentId(shipment.getId());
                products.forEach(p->{
                    OprPickup oprPickup = oprPickupMapper.selectOprPickupById(p.getPickupId());
                    if(p.getCompanionId() == null){
                        merchantAsync.backProductState(ProductStatus.builder()
                                .pickupNo(oprPickup.getChPickupNo())
                                .barcode(p.getBarcode())
                                .status(OprProductType.SHIPPED.name())
                                .state(0).noWash(false).build(), oprPickup.getChannelId());
                    }
                });
                merchantAsync.backShipState(ShipmentStatus.builder().shipmentNo(shipment.getChShipmentNo()).status(ShipMentType.SHIPPED.name()).build(), shipment.getChannelId());
            });
        }
        return success();
    }
*/


   /* @PostMapping("/id")
    //@RoleAnnotation(value = UserRoleType.ZYYG)
    public AjaxResult getUserById(Long userId){
        return AjaxResult.success(userService.getUserById(userId));
    }
    @PostMapping("/flag")
    public AjaxResult getList(){
        return AjaxResult.success(userService.getList());
    }
*/


//    @PostMapping("/create")
//    public AjaxResult send() {
//        return success(tktTicketService.addPlatform(TicketFactory.builder()
//                .ticketId(10)
//                .barcode("1300100000436")
//                .comment("数量不符")
//                .label("工单标签")
//                .priority("HIGH")
//                .orderNo("R022344319276083")
//                .title("数量不符")
//                .type(FlowType.LOSE_LESS.name())
//                .eventType(RouteKey.TICKETNEW.name())
//                .build()));
//    }
//
//
//    @PostMapping("/fin")
//    public AjaxResult fin(){
//       return success(tktTicketService.backTicket(TicketBackVo.builder()
//               .ticketId(9l)
//               .remark("已知悉")
//               .ticketBackState(TicketBackStatus.HAVEKNOWN.name())
//               .build()));
//    }


//    @PostMapping("/third")
//    public AjaxResult thrid(String pickupNo,String code){
//        ResponseEntity response = thirdChannelService.updateMerchandises(pickupNo, code);
//        return success(response);
//    }


    /**
     * 入厂单添加商品
     */
/*
    @PostMapping("/pickup/{pickupNo}/merchandises")
    public ResponseEntity addMerchandises(@PathVariable String pickupNo, @RequestBody List<MerchandiseItem> merchandises){
        System.out.println("asdasd");
        return thirdChannelService.addMerchandises(pickupNo,merchandises);
    }



  /*  @PostMapping("/msg")
    public AjaxResult getUserById() throws NoSuchAlgorithmException, InvalidKeyException {
       *//* String url = "http://localhost:9563/car/testSS";
        OprProduct product = new OprProduct();
        product.setId(1l);
        product.setBarcode("123123123");
        product.setFrameNo("asdasd");
        MessageVo vo = new MessageVo();
        vo.setMsg("success");
        vo.setTime(DateUtils.dateTimeNow());
        vo.setCode("2");
        vo.setData(product);
        String str = JSONObject.toJSONString(vo);
        System.out.println(str);
        return AjaxResult.success(HttpUtils.sendMsg(url,vo));*//*

         public static void main(String[] args) {
        BarcodeVo vo = new BarcodeVo();
        vo.setBarcode("1300100000016");
        vo.setWashMode(ParamType.NOWASH.name());
        ArrayList<TktTicketFile> files = new ArrayList<>();
        TktTicketFile.builder().fileUrl("asdasdasdas").fileType("asda").remark("这是备注").build();
        files.add(TktTicketFile.builder().fileUrl("asdasdasdas").fileType("asda").remark("这是备注").build());
        ArrayList<BarcodeVo> vos = new ArrayList<>();
        vos.add(vo);
        TicketBackVo backVo = new TicketBackVo();
        backVo.setTicketId(1106l);
        backVo.setTicketBackState(TicketBackStatus.BEFOREWASH.name());
        backVo.setBarcodeVos(vos);
        backVo.setTktTicketFiles(files);

        String string = JSONObject.toJSONString(backVo);
        System.out.println(string);
    }

       return AjaxResult.success(new HttpTest().testHead());
    }
*/


   /* *//**
     * 平台添加工单
     */
  /*  @PostMapping("/ticket")
    public ResponseEntity addPlatform(@RequestBody  TicketFactory ticketFactory) {
        return tktTicketService.addPlatform(ticketFactory);
    }*/



//  /*  @PostMapping("/user")
//    public AjaxResult testMethod(TicketBackVo ticketBackVo) throws Exception {
//      return detectMethodAnnotation.execute(merchantAsync,ticketBackVo.getTicketBackState(),ticketBackVo);
//    }*/

//    @PostMapping("/test")
//    public AjaxResult testMethod(){
//        OprProduct build = OprProduct.builder().build();
//        build.setId(115l);
//        build.setStatus(OprProductType.TOINSPECT.getValue());
//        build.setWashMode(ParamType.FINEWASH.name());
//        oprProductMapper.updateStatueById(build);
//        return AjaxResult.success();
//    }



}
